package zjw.springboot2.test.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

@Slf4j
public class YundaoClient {
    private String serviceURL;

    private String params;

    public YundaoClient(String serviceURL, String params) {
        this.serviceURL = serviceURL;
        this.params = params;
    }

    /**
     * 调用奇门接口方法
     *
     * @return
     */
    public HttpResponse connect() {
        String result = "";
        HttpResponse httpResponse = new HttpResponse();
        try {
            String url = serviceURL + "?" + params;
            httpResponse.setUrl(url);
            String originalUrl = serviceURL + "?" + params;
            httpResponse.setOriginalUrl(originalUrl);
            RequestConfig.Builder requestBuilder = RequestConfig.custom();
            requestBuilder = requestBuilder.setConnectionRequestTimeout(60000);
            requestBuilder = requestBuilder.setConnectTimeout(10000);
            HttpClientBuilder builder = HttpClientBuilder.create();
            builder.setDefaultRequestConfig(requestBuilder.build());
            HttpClient client = builder.build();
            HttpPost post = new HttpPost(url);
            org.apache.http.HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            } else {
                result = response.toString();
            }
            httpResponse.setCode(response.getStatusLine().getStatusCode());
            httpResponse.setBody(result);
        } catch (Exception e) {
            log.error("method connect exception {}", e);
            httpResponse.setCode(-1);
            httpResponse.setBody(e.toString());
        }
        return httpResponse;
    }
}
